package com.wdb007.venus.wss.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;

@Service("bookCaseStatusResService")
public class BookCaseStatusResService implements WebSocketServerService {

	private static Logger logger = LoggerFactory.getLogger(BookCaseStatusResService.class);
	@Autowired
	private ProcessInstructionService processInstructionService;	
	@Autowired
	private BookgridService bookgridService;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		JSONObject jsonObj = JSON.parseObject(request);
//		logger.info("BookCaseStatusRes 接收websocket响应信息: {}", jsonObj.toJSONString());
		try {
			//1.首先根据pushId来判断是否已经处理，如果已经处理，则不做任何处理。
			logger.info("debug {}: 响应内容{}", jsonObj.getString("action"), jsonObj.toJSONString());
			String bookCaseId = BookCaseChannelGroups.getBookCaseId(ctx.channel());
			String pushId = jsonObj.getString("pushId");
			ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookCaseId);
			pi.setInstructionGroupId(Long.valueOf(pushId));
			processInstructionService.bookCaseUnlockRes(pi);
			//2.数据处理
			Map<String, String> statuses = (Map<String, String>) jsonObj.get("statuses");
			bookgridService.bookCaseStatusReport(statuses);
			
		} catch (Exception e) {
			logger.error("整书柜状态上报异常", e);
		}
		return null;
	}

}
